package com.mlethe.android.demo.banner;

import android.os.Bundle;
import android.util.SparseArray;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.mlethe.android.demo.R;
import com.mlethe.android.demo.banner.adapter.ViewPagerAdapter;

public class FragmentActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private String[] mTitles;
    private SparseArray<Fragment> fragments = new SparseArray<>();
    private ViewPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_banner_fragment);
        tabLayout = findViewById(R.id.test_tab);
        viewPager = findViewById(R.id.test_vp);
        mTitles = new String[]{"页面一","页面二","页面三","页面四","页面五"};
        setView();
    }

    /**
     * 初始化view
     */
    private void setView(){
        fragments.clear();
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), mTitles);
        viewPager.setAdapter(adapter);
        // 设置预加载界面个数
        viewPager.setOffscreenPageLimit(1);
        tabLayout.setupWithViewPager(viewPager);
        initTab();
        adapter.notifyDataSetChanged();
    }

    private void initTab() {
        tabLayout.removeAllTabs();
        for (int i = 0; i < mTitles.length; i++) {
            tabLayout.addTab(tabLayout.newTab().setText(mTitles[i]));
        }
    }
}
